package com.zyz.sunliky.service.serviceImpl;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zyz.sunliky.entity.InkmmModelGysb;
import com.zyz.sunliky.entity.InkmmModelGysdz;
import com.zyz.sunliky.entity.InkmmModelGysyx;
import com.zyz.sunliky.mapper.erp.ErpMapper;
import com.zyz.sunliky.mapper.yunshu.DepartmentMapper;
import com.zyz.sunliky.mapper.yunshu.SupplierMapper;
import com.zyz.sunliky.service.SupplierService;
import com.zyz.sunliky.util.LoginUtils;
import com.zyz.sunliky.util.UUIDUtils;
import jakarta.transaction.Transactional;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class SupplierServiceImpl implements  SupplierService {
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger(SupplierService.class);
    @Autowired
    ErpMapper erpMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Value("${spring.yunshuurl}")
    private String URL;
    @Autowired
    SupplierMapper supplierMapper;
    @Override
    public Map getOrderInfo(String supplierNo, int page, int rows) {
        logger.info("aaa");
        Map map = new HashMap();
        List<Map> listSort  = new ArrayList<>();
        //List<Map> listSort  = new ArrayList<>();
        List<Map> erplist = erpMapper.getOrderInfo(supplierNo);
        int size=erplist.size();
        if(page == 0){
            page = 1;
        }
        int pageStart=page==1?0:(page-1)*rows;//截取的开始位置
        int pageEnd=size<page*rows?size:page*rows;//截取的结束位置
        if(size>pageStart){
            listSort =erplist.subList(pageStart, pageEnd);
        }
        //总页数
        int totalPage=erplist.size()/rows;
        map.put("count",erplist.size());
        map.put("data",listSort);
        return map;
    }

    @Override
    public String projectNum(String projectType) {
        System.out.println("projectType");
        String aa = erpMapper.project(projectType);
        return aa ;
    }

    /**
     * 同步供应商信息
     */
    @Transactional
    @Override
    public void saveSupplier() {
        Date date = new Date();
        List<Map> mapList = new ArrayList<>();
        //查erp供应商订单行信息
        List<Map> orderList = erpMapper.get0rderLine();
        List<String> ys0rderList = supplierMapper.get0rderLine();
        System.out.println("供应商订单行信息");
        //判断中间表是否存在这条数据
        for (Map map:orderList) {

            if (!ys0rderList.contains(map.get("UUID"))) {
                //设置owner
                String owner = supplierMapper.getOwner(map.get("DDGYS").toString());
                System.out.println("owner" + owner);
                if (owner == null) {
                    owner = ""; // 将 owner 设置为空字符串
                    logger.info("表中没有供应商信息");
                }
                map.put("owner",owner);
                map.put("createdTime",date);
                map.put("creater","456ec86ba4754816a5814ba3cf1e5d7c");
                mapList.add(map);
            }
        }

       // int num = supplierMapper.insertDeparment(departList);
        if (mapList.size() != 0) {
            int num = supplierMapper.insertOrder(mapList);
            System.out.println("更新" + num + "条");
        }

    }

    @Transactional
    @Override
    public void getSupplier(String id) {
        System.out.println("aa");
        Map<String, Object> supplier = supplierMapper.getSupplier(id);
        System.out.println(supplier);
        if (supplier == null || supplier.get("supplierCode") == null || StringUtils.isEmpty(supplier.get("supplierCode").toString())) {
            throw new RuntimeException("无法找到或供应商编号为空！供应商ID：" + id);
        }
        String supplierCode = supplier.get("supplierCode").toString();

        Map erpSupplier = erpMapper.getErpSupplier(supplierCode);
        InkmmModelGysb inkmmModelGysb =  new InkmmModelGysb();
        InkmmModelGysdz inkmmModelGysdz =  new InkmmModelGysdz();
        InkmmModelGysyx inkmmModelGysyx =  new InkmmModelGysyx();
        if (erpSupplier.isEmpty()) {
            throw new RuntimeException("erp供应商信息查询失败！");
        }
        inkmmModelGysb.setId(supplierCode);
        inkmmModelGysb.setCreater("8a8a82ef828f9a7b01828fa077ea0000");
        inkmmModelGysb.setOwner("8a8a82ef828f9a7b01828fa077ea0000");
        inkmmModelGysb.setSequencestatus("COMPLETED");
        inkmmModelGysb.setFlb(erpSupplier.get("FLB") != null ? erpSupplier.get("FLB").toString().toUpperCase() : "");
        inkmmModelGysb.setFsfjh(erpSupplier.get("FSFJH") != null ? erpSupplier.get("FSFJH").toString().toUpperCase() : "");
        inkmmModelGysb.setFkhdm(supplierCode);
        inkmmModelGysb.setFkhmc(erpSupplier.get("FKHMC") != null ? erpSupplier.get("FKHMC").toString().toUpperCase() : "");
        inkmmModelGysb.setFkhzt(erpSupplier.get("FKHZT") != null ? erpSupplier.get("FKHZT").toString().toUpperCase() : "");
        inkmmModelGysb.setFhb(erpSupplier.get("FHB") != null ? erpSupplier.get("FHB").toString().toUpperCase() : "");
        inkmmModelGysb.setFfpkhbm(erpSupplier.get("FFPKHBM") != null ? erpSupplier.get("FFPKHBM").toString().toUpperCase() : "");
        inkmmModelGysb.setFfpdz(erpSupplier.get("FFPDZ") != null ? erpSupplier.get("FFPDZ").toString().toUpperCase() : "");
        inkmmModelGysb.setFfkkh(erpSupplier.get("FFKKH") != null ? erpSupplier.get("FFKKH").toString().toUpperCase() : "");
        inkmmModelGysb.setFfkkhdz(erpSupplier.get("FFKKHDZ") != null ? erpSupplier.get("FFKKHDZ").toString().toUpperCase() : "");
        inkmmModelGysb.setFsz(erpSupplier.get("FSZ") != null ? erpSupplier.get("FSZ").toString().toUpperCase() : "");
        inkmmModelGysb.setFhsbhs(erpSupplier.get("FHSBHS") != null ? erpSupplier.get("FHSBHS").toString().toUpperCase() : "");
        inkmmModelGysb.setFfktj(erpSupplier.get("FFKTJ") != null ? erpSupplier.get("FFKTJ").toString().toUpperCase() : "");
        inkmmModelGysb.setFfhms(erpSupplier.get("FFHMS") != null ? erpSupplier.get("FFHMS").toString().toUpperCase() : "");
        inkmmModelGysb.setFgj(supplier.get("countryCode") != null ? supplier.get("countryCode").toString().toUpperCase() : "");
        inkmmModelGysb.setFyy(supplier.get("lanCode") != null ? supplier.get("lanCode").toString().toUpperCase() : "");
        //inkmmModelGysb.setFgj(erpSupplier.get("fgj") != null ? erpSupplier.get("fgj").toString() : "");
        //inkmmModelGysb.setFyy(erpSupplier.get("fyy") != null ? erpSupplier.get("fyy").toString() : "");

        //供应商地址
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        System.out.println(uuid);
        inkmmModelGysdz.setId(String.valueOf(uuid));
        inkmmModelGysdz.setCreater("8a8a82ef828f9a7b01828fa077ea0000");
        inkmmModelGysdz.setOwner("8a8a82ef828f9a7b01828fa077ea0000");
        inkmmModelGysdz.setCreatedtime(new Date());
        inkmmModelGysdz.setSequencestatus("COMPLETED");
        inkmmModelGysdz.setFkhdm(supplierCode);
       // inkmmModelGysdz.setFdzdm(erpSupplier.get("ffkkhdz").toString());
        inkmmModelGysdz.setFdzdm(erpSupplier.get("FFKKHDZ") != null ? erpSupplier.get("FFKKHDZ").toString() : "");
        inkmmModelGysdz.setFdz(supplier.get("address").toString());
        inkmmModelGysdz.setFdh(supplier.get("tel").toString());
        inkmmModelGysdz.setFlxr(supplier.get("supplierContact").toString());
        inkmmModelGysdz.setFsfmrdz("2");
        //供应商邮箱
        String uid = UUID.randomUUID().toString().replaceAll("-","");
        inkmmModelGysyx.setId(String.valueOf(uid));
        inkmmModelGysyx.setCreater("8a8a82ef828f9a7b01828fa077ea0000");
        inkmmModelGysyx.setOwner("8a8a82ef828f9a7b01828fa077ea0000");
        inkmmModelGysyx.setSequencestatus("COMPLETED");
        inkmmModelGysyx.setFgysdm(supplierCode);
        //inkmmModelGysyx.setFgysmc(erpSupplier.get("fkhmc").toString());
        inkmmModelGysyx.setFgysmc(erpSupplier.get("FKHMC") != null ? erpSupplier.get("FKHMC").toString() : "");
        inkmmModelGysyx.setFlxr(supplier.get("supplierContact").toString());
        inkmmModelGysyx.setFlx("1");
        inkmmModelGysyx.setFyx(supplier.get("email").toString());

        String suppCode = supplierMapper.getSupplierCode(supplierCode);
        if (!StringUtils.isEmpty(suppCode)){
            throw new RuntimeException("供应商"+ supplierCode + "已存在！");
        }
            int count  = supplierMapper.saveGysb(inkmmModelGysb);
            int count1 = supplierMapper.saveGysdz(inkmmModelGysdz);
            int count2 = supplierMapper.saveGysyx(inkmmModelGysyx);

    }

    /**
     * 同步采购收货
     */
    @Transactional
    @Override
    public void purchaseReceipt() throws ParseException {
        //Date date = new Date();
        //同步收货表头信息
         List<Map> headList = supplierMapper.getReceiptHead();
        //List<Map> bodyList = supplierMapper.getReceiptBody();
        List<String> erpHeadList = erpMapper.erpHeadList();
        System.out.println("供应商收货信息");

        //判断中间表是否存在这条数据
        for (Map map:headList) {
            //if (map!=null){
            if (map.get("voucher_no") != null && !erpHeadList.contains(map.get("voucher_no"))) {
                List<Map> mapList = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                map.put("iptdat", sdf.format(new Date()));
                String dateConversion = map.get("modifiedTime").toString();

                String formattedDateTime = conversionDate(dateConversion);
                map.put("createTime", formattedDateTime);


                String uuid = UUID.randomUUID().toString().replaceAll("-","");
                //凭证号确定唯一
            //if (map.get("voucher_no") != null && !erpHeadList.contains(map.get("voucher_no"))) {}
                System.out.println("随机生成的 UUID: " + uuid);
                //设置owner
                //String owner = supplierMapper.getOwner(map.get("DDGYS").toString());
                map.put("uuid",uuid);
                int num = erpMapper.insertReceiptHead(map);
                System.out.println("更新供应商收货信息表头,凭证号：" +map.get("voucher_no"));

                //采购明细表同步  按凭证号批量插入
                String voucherNo = map.get("voucher_no").toString();
                List<Map> bodyList = supplierMapper.getReceiptBody(voucherNo);
                for (Map m : bodyList){
                    if (null != m){
                        String modifiedTime = conversionDate(m.get("modifiedTime").toString());
                        m.put("modifiedTime", modifiedTime);
                        LocalDateTime originalDateTime = LocalDateTime.parse(m.get("produceDate").toString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);

                        // 创建自定义的日期时间格式
                        DateTimeFormatter newFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                        // 格式化 LocalDateTime 对象为新的日期时间字符串
                        String produceDate = originalDateTime.format(newFormat);

                        System.out.println("转换后的日期时间字符串: " + produceDate);
                        System.out.println(produceDate);
//                        String produceDate =  conversionDate(m.get("produceDate").toString());
                        m.put("produceDate", produceDate);
                    }
                    mapList.add(m);
                }

                    int erpnum = erpMapper.addReceiptDetail(mapList);
                logger.info("采购明细更新了" + erpnum + "条数据！");
            }
        }
        System.out.println("遍历结束");
        // int num = supplierMapper.insertDeparment(departList);
//        if (mapList.size() != 0) {
//            int num = erpMapper.insertReceiptHead(mapList);
//            System.out.println("更新供应商收货信息表头" + num + "条");
//        }
    }


    @Override
    public void saveRreport() {
         String WorkflowCode = "";
         //先查审批驳回的 重新发送
        //List<Map<String, Object>> rejectList = supplierMapper.getrejectList();
        //查
//        if (rejectList != null && !rejectList.isEmpty()) {
//            for (Map<String, Object> rej : rejectList) {
//                if ("立项".equals(rej.get("fjdmc").toString())) {
//                    WorkflowCode = "project_review_approval";
//                    sendRequest(rej,WorkflowCode);
//                    //作废掉原先的流程  pid
//
//                }else  if ("原型设计".equals(rej.get("fjdmc").toString())) {
//                    WorkflowCode = "project_review_test";
//                    sendRequest(rej, WorkflowCode);
//                }else  if ("上市".equals(rej.get("fjdmc").toString())) {
//                    WorkflowCode = "project_review_list";
//                    sendRequest(rej, WorkflowCode);
//                }
//
//            }
//        }
        //查询项目-阶段信息
        List<Map<String, Object>> projectList = supplierMapper.getProjectList();
        if (projectList != null && !projectList.isEmpty()) {
            for (Map<String, Object> listMx : projectList) {
                if ("概念评估".equals(listMx.get("stage_name").toString())) {
                    String jd = supplierMapper.getJid(listMx.get("yf_id").toString());
                    // Check if jdid is not null and not empty
                    if (jd == null || jd.isEmpty()) {
                        WorkflowCode = "project_report";
                        sendRequest(listMx,WorkflowCode);
                    }
                }else if ("候选品开发".equals(listMx.get("stage_name").toString())){
                    //立项已完成 才能发起大线试车审批
                    Map<String, Object> jdid = supplierMapper.getPid(listMx.get("project_id").toString());
                    Object statusObj = jdid.get("stage_status");
                    if (statusObj != null && "已完成".equals(String.valueOf(statusObj))) {
                        String jd = supplierMapper.getJid(listMx.get("yf_id").toString());
                        if (jd == null || jd.isEmpty()) {
                            WorkflowCode = "project_report";
                            sendRequest(listMx, WorkflowCode);
                        }
                    }
                    else {
                        //立项未完成 重新发起立项审批
                        String jd = supplierMapper.getJid(jdid.get("id").toString());
                        if (jd == null || jd.isEmpty()) {
                            WorkflowCode = "project_report";
                            listMx.put("yf_id",jdid.get("id"));
                            listMx.put("fjdfzr",jdid.get("stage_user"));
                            listMx.put("stage_name",jdid.get("fjdmc"));
                            listMx.put("start_time",jdid.get("fkssj"));
                            listMx.put("end_time",jdid.get("fjssj"));
                            sendRequest(listMx,WorkflowCode);
                        }
                    }

                }else if ("上市".equals(listMx.get("stage_name").toString())){
                    //立项已完成 大线试车已完成 才能发起上市审批
                    Map<String, Object> jdid = supplierMapper.getDid(listMx.get("project_id").toString());
                    Object statusObj = jdid.get("stage_status");
                    if (statusObj != null && "已完成".equals(String.valueOf(statusObj))) {
                        String jd = supplierMapper.getJid(listMx.get("yf_id").toString());
                        if (jd == null || jd.isEmpty()) {
                            WorkflowCode = "project_report";
                            sendRequest(listMx, WorkflowCode);
                        }

                    }else {
                        //大线试车未完成 重新发起立项审批
                        Map<String, Object> did = supplierMapper.getPid(listMx.get("project_id").toString());
                        Object statusDid = did.get("stage_status");
                        if (statusDid != null && "已完成".equals(String.valueOf(statusDid))) {
                            String jd = supplierMapper.getJid(jdid.get("id").toString());
                            if (jd == null || jd.isEmpty()) {
                                listMx.put("yf_id",jdid.get("id"));
                                listMx.put("fjdfzr",jdid.get("stage_user"));
                                listMx.put("stage_name",jdid.get("fjdmc"));
                                listMx.put("start_time",jdid.get("fkssj"));
                                listMx.put("end_time",jdid.get("fjssj"));
                                WorkflowCode = "project_report";
                                sendRequest(listMx, WorkflowCode);
                            }
                        }else {
                            String jd = supplierMapper.getJid(did.get("id").toString());
                            if (jd == null || jd.isEmpty()) {
                                listMx.put("yf_id",did.get("id"));
                                listMx.put("fjdfzr",did.get("stage_user"));
                                listMx.put("stage_name",did.get("fjdmc"));
                                listMx.put("start_time",did.get("fkssj"));
                                listMx.put("end_time",did.get("fjssj"));
                                WorkflowCode = "project_report";
                                sendRequest(listMx,WorkflowCode);
                            }

                        }

                    }
                }
                //todo
            }
        }


    }

    public void sendRequest(Map<String, Object> req,String WorkflowCode){
        /**查询用户名称**/
        //String username=purchaseMapper.findUserName(id);
        //if(StringUtils.isEmpty(username))throw new RuntimeException("用户不存在");
        JSONObject object = JSON.parseObject("{\n" +
                "  \"finishStart\":true,\n" +
                "  \"username\":\"admin\"\n" +
                "}");
        object.put("workflowCode", WorkflowCode);
        String getuuid = UUIDUtils.getuuid();
        JSONObject data=new JSONObject();
        data.put("id", getuuid);
        req.forEach((key,value)->{
            data.put(String.valueOf(key),value);
        });
        String name = "进度汇报";
        //String name = req.get("project_name").toString() + "项目" + req.get("stage_name").toString() + "阶段";
        data.put("name", name);
//        data.put("fjdid",req.get("id").toString());
//        data.put("fxmh",req.get("fxmh").toString());
//        Date date = new Date();
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
//        String formattedDate = formatter.format(date);
//        System.out.println(formattedDate);
//        data.put("fpssj",formattedDate);
//        data.put("fysje",req.get("fxmje").toString());
//        data.put("fxmmc",req.get("fxmmc").toString());
//        data.put("fjdfzr",req.get("stage_user").toString());
//        data.put("fcpxfzr",req.get("fbufzr").toString());
//        data.put("fxmjl",req.get("fxmjl").toString());
//        data.put("fxmzq","100");
//        data.put("fjdmc",req.get("fjdmc").toString());
       // LocalDateTime currentDateTime = LocalDateTime.now();

        // 格式化输出
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//        String formattedDateTime = currentDateTime.format(formatter);
//        System.out.println("当前时间（到分钟）：" + formattedDateTime);
//        data.put("date", formattedDateTime);
        object.put("data",data);
        System.out.println(data);
        String s = object.toJSONString();
        String postResult = HttpRequest
                .post(URL+"/api/api/runtime/form/start_workflow")
                .header("Content-Type","application/json")
                .header("Authorization", "Bearer "+ LoginUtils.gettoken("1"))
                .body(s)
                .execute()
                .body();

    }
    String conversionDate(String dateConversion) throws ParseException {

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
//                Date date = sdf1.parse(map.get("modifiedTime").toString());
//                java.sql.Timestamp timestamp = new Timestamp(date.getTime());
        Date date = sdf1.parse(dateConversion);
        SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = sdfOutput.format(date);
        return formattedDateTime;
    }
}
